package com.java.teacherexer.exer3;

import javax.swing.*;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    //定义socket对象
    private static Socket sc;
    //定义输出流，发送消息
    private static OutputStream outs;
    private static ObjectOutputStream objOut;
    //定义输入流，接收消息
    private static InputStream ins;
    private static ObjectInputStream objIn;

    public static void main(String[] args) {
        while (true) {
            String input = JOptionPane.showInputDialog("请输入你要发送的消息：");
            if (input == null) {
                break;
            }
            try {
                sc = new Socket("192.168.13.5", 9527);
                //建立输出流通道
                outs = sc.getOutputStream();
                objOut = new ObjectOutputStream(outs);
                //输出消息对象
                objOut.writeObject(input);
                //接收回执消息
                ins = sc.getInputStream();
                objIn = new ObjectInputStream(ins);
                Object msg = objIn.readObject();

                JOptionPane.showMessageDialog(null, msg);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (ins != null) {
                    try {
                        ins.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (outs != null) {
                    try {
                        outs.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
        //退出
        System.exit(0);
    }

}
